<template>
  <!-- 添加应用策略明细 -->
  <a-modal :width="1200" v-model:visible="showPolicyItemDetail" :title="`应用策略-${PolicyType[currentData.policyType]}`" :on-before-ok="submitData" :ok-loading="submitLoading" title-align="start" :mask-closable="false" @cancel="closedDialog">
    <a-form style="margin-bottom: 10px" ref="formRef" :model="currentData">
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item field="policyName" label="策略名称：" label-col-flex="100px">
            <p>{{ currentData.policyName }}</p>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="生效日期：" label-col-flex="100px">
            <p v-if="!currentData.effectiveEndDate && !currentData.effectiveStartDate">一直有效</p>
            <p v-else>{{ currentData.effectiveStartDate }}~{{ currentData.effectiveEndDate }}</p>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item field="isShare" label="是否共享：" label-col-flex="100px">
            <p>{{ currentData.isShare === 1 ? '共享' : '不共享' }}</p>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item field="marketplaceIds" label="适用站点：" label-col-flex="100px">
            <p>{{ getMarketplace(currentData.applicableMarketplace) }}</p>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item field="isShare" :label="`原始${PolicyTypeText[currentData.policyType]}：`" label-col-flex="100px">
            <p>
              <span style="margin-right: 10px">{{ PolicyOriginType[currentData.budgetType] }}</span>
              <span class="highlight" v-if="currentData.budgetType === 'FIXED_BUDGET'">$ {{ currentData.fixedBudgetAmount }}</span>
            </p>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item field="marketplaceIds" label="调整频率：" label-col-flex="100px">
            <PolicyRuleDetail className="text-limit" :policyType="currentData.policyType" :detail="currentData" :ruleList="currentData.policyTemplateRuleDOS" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="24">
          <a-form-item field="isShare" :label="`${PolicyTypeText[currentData.policyType]}回调：`" label-col-flex="100px">
            <p v-if="currentData.isPolicyCallback === 2">不回调</p>
            <p v-else>
              <!-- 竞价和预算 -->
              <span style="margin-right: 10px">生效时间结束后，将每个对象的{{ PolicyTypeText[currentData.policyType] }}调整为</span>
              <template v-if="currentData.policyType == 'BUDGET_POLICY' || currentData.policyType == 'BIDDING_POLICY'">
                <span style="margin-right: 5px">{{ currentData.isPolicyCallback === 0 ? '基准值' : '固定值' }}</span>
                <span class="highlight">$ {{ currentData.fixedCallbackAmount }}</span>
              </template>
              <!-- 状态 -->
              <template v-else-if="currentData.policyType == 'SWITCH_POLICY'">
                <span style="margin-right: 5px">{{ currentData.isPolicyCallback === 0 ? '原始状态' : '固定状态' }}</span>
                <span v-if="currentData.isPolicyCallback === 1" class="highlight">{{ currentData.fixedCallbackValue === 'ENABLED' ? '启用' : '暂停' }}</span>
              </template>
              <!-- 广告位 -->
              <template v-else-if="currentData.policyType == 'TARGETING_POLICY'">
                <span style="margin-right: 5px">原价</span>
              </template>
            </p>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <div class="flex-c" style="margin-bottom: 10px">
      <span>使用方式：</span>
      <a-radio-group v-model="targetingType" @change="changeTargetingType">
        <!-- 竞价显示关键字和商品投放，其他显示广告活动 -->
        <a-radio value="CAMPAIGN" v-if="currentData.policyType != 'BIDDING_POLICY'">广告活动</a-radio>
        <template v-else>
          <a-radio value="KEYWORD">关键字</a-radio>
          <a-radio value="PRODUCT_TARGETING">商品投放</a-radio>
        </template>
      </a-radio-group>
    </div>
    <div class="filter-list flex-c">
      <template v-for="(item, i) in filterItem" :key="i">
        <div class="filter-item">
          <template v-if="item.type == 'input_search'">
            <a-input-search v-model="item.value" :style="{ width: item.width + 'px' }" :placeholder="item.placeholder || item.label" allow-clear @press-enter="startSearchByVal" @clear="startSearchByVal" @search="startSearchByVal" />
          </template>
          <template v-else-if="item.type == 'select_multiple'">
            <selectMultiple :key="item.key" :info="item" :defaultVal="item.value" @change="selectMulVal($event, item)" />
          </template>
        </div>
      </template>
    </div>
    <div class="flex-c-sb">
      <div style="width: 570px">
        <a-table class="table-singe-line" ref="tableRef" :row-key="targetingType == 'KEYWORD' ? 'keywordId' : 'targetId'" :loading="tableLoading" @selection-change="selectColumn" :row-selection="rowSelection" :data="tableList" :scroll="{ x: '100%', y: 'calc(84vh - 400px)' }" size="mini" :pagination="false">
          <template #columns>
            <a-table-column title="店铺" :width="100" data-index="shopName" :ellipsis="true" :tooltip="true" />
            <a-table-column title="投放" v-if="targetingType == 'KEYWORD'">
              <template #cell="{ record }">
                <p>{{ KeywordMatchType[record.matchType] }}匹配</p>
                <a-tooltip :content="record.keywordText">
                  <p class="text-limit">{{ record.keywordText }}</p>
                </a-tooltip>
              </template>
            </a-table-column>
            <a-table-column title="投放" v-if="targetingType == 'PRODUCT_TARGETING'">
              <template #cell="{ record }">
                <p v-if="record.adType === 'SPONSORED_BRANDS'">{{ record.campaignName }}</p>
                <p v-else>{{ record.targetingResolvedExpressionValue }}</p>
              </template>
            </a-table-column>
            <a-table-column title="广告活动">
              <template #cell="{ record }">
                <div class="flex">
                  <a-tag size="small" style="padding: 0 2px; flex-shrink: 0" color="arcoblue">{{ AdTypesTag[record.adType] }}</a-tag>
                  <a-tooltip :content="record.campaignName">
                    <p class="text-limit-two">{{ record.campaignName }}</p>
                  </a-tooltip>
                </div>
              </template>
            </a-table-column>
            <a-table-column title="广告组" v-if="targetingType != 'CAMPAIGN'" data-index="adGroupName" :ellipsis="true" :tooltip="true" />
            <a-table-column title="活动状态" :width="70" align="center">
              <template #cell="{ record }">
                <p>{{ AdStatus[record.state] }}</p>
              </template>
            </a-table-column>
            <a-table-column :width="70" align="center">
              <template #title>
                <p class="highlight cursor" @click="addItem(tableList)">全部添加</p>
              </template>
              <template #cell="{ record }">
                <a-button type="text" @click="addItem([record])">添加</a-button>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </div>
      <div style="width: 570px; position: relative">
        <span class="checked-num" v-if="checkedTableList.length">已选{{ checkedTableList.length }}</span>
        <a-table class="table-singe-line" :data="checkedTableList" :scroll="{ x: '100%', y: 'calc(84vh - 400px)' }" size="mini" :pagination="false">
          <template #columns>
            <a-table-column title="店铺" :width="100" data-index="shopName" :ellipsis="true" :tooltip="true" />
            <a-table-column title="投放" v-if="targetingType == 'KEYWORD'">
              <template #cell="{ record }">
                <p>{{ KeywordMatchType[record.matchType] }}匹配</p>
                <a-tooltip :content="record.keywordText">
                  <p class="text-limit">{{ record.keywordText }}</p>
                </a-tooltip>
              </template>
            </a-table-column>
            <a-table-column title="投放" v-if="targetingType == 'PRODUCT_TARGETING'">
              <template #cell="{ record }">
                <p v-if="record.adType === 'SPONSORED_BRANDS'">{{ record.campaignName }}</p>
                <p v-else>{{ record.targetingResolvedExpressionValue }}</p>
              </template>
            </a-table-column>
            <a-table-column title="广告活动">
              <template #cell="{ record }">
                <div class="flex">
                  <a-tag size="small" style="padding: 0 2px; flex-shrink: 0" color="arcoblue">{{ AdTypesTag[record.adType] }}</a-tag>
                  <a-tooltip :content="record.campaignName">
                    <p class="text-limit-two">{{ record.campaignName }}</p>
                  </a-tooltip>
                </div>
              </template>
            </a-table-column>
            <a-table-column title="广告组" data-index="adGroupName" v-if="targetingType != 'CAMPAIGN'" :ellipsis="true" :tooltip="true" />
            <a-table-column title="活动状态" :width="70" align="center">
              <template #cell="{ record }">
                <p>{{ AdStatus[record.state] }}</p>
              </template>
            </a-table-column>
            <a-table-column :width="80" align="center">
              <template #title>
                <p class="highlight cursor" @click="checkedTableList = []">全部移除</p>
              </template>
              <template #cell="{ rowIndex }">
                <a-button type="text" @click="checkedTableList.splice(rowIndex, 1)">移除</a-button>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </div>
    </div>
    <div style="margin-top: 10px">
      <a-pagination size="mini" :total="total" :default-page-size="paginationVal.pageSize" :current="paginationVal.pageNum" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size @page-size-change="sizeChange" @change="changePage" />
    </div>
  </a-modal>
</template>
<script lang="ts" setup>
  import { ref, onMounted, reactive, PropType, watchEffect } from 'vue'
  import { PolicyType, PolicyBudgetType, PolicyBidType, AdStatus, AdTypesTag, KeywordMatchType, PolicyTypeText } from '../../types'
  import { marketPlaceList } from '@/utils/globalData'
  import { getCampaignBaseList, savePolicyTargeting, getKeywordBaseList, getTargetingBaseList } from '@/api/advert'
  import { Message } from '@arco-design/web-vue'
  import { FilterTableItem } from '@/types/components'
  import PolicyRuleDetail from './policyRuleDetail.vue'

  const emit = defineEmits(['closed', 'success'])
  const props = defineProps({
    isShow: {
      type: Boolean,
      default: false,
    },
    shopList: {
      type: Array as PropType<Array<any>>,
      default: () => [],
    },
    currentData: {
      type: Object,
      default: () => {},
    },
  })
  onMounted(async () => {
    // 应用类型： 竞价模板默认关键字，其他默认广告活动
    targetingType.value = props.currentData.policyType === 'BIDDING_POLICY' ? 'KEYWORD' : 'CAMPAIGN'
    getTableList()
  })
  const filterItem = ref<Array<FilterTableItem>>([
    {
      key: 'shopIds',
      label: '全部店铺',
      value: ref(),
      type: 'select_multiple',
      width: 120,
      optionItems: [],
    },
    {
      key: 'adTypes',
      label: '广告类型',
      value: ref(),
      type: 'select_multiple',
      width: 120,
      optionItems: [
        {
          label: '商品广告',
          value: 'SPONSORED_PRODUCTS',
        },
        {
          label: '品牌广告',
          value: 'SPONSORED_BRANDS',
        },
        {
          label: '展示广告',
          value: 'SPONSORED_DISPLAY',
        },
      ],
    },
    {
      key: 'campaignName',
      label: '广告活动',
      value: ref(),
      type: 'input_search',
      width: 200,
    },
  ])
  const PolicyOriginType = props.currentData.policyType === 'BIDDING_POLICY' ? PolicyBidType : PolicyBudgetType
  const showPolicyItemDetail = ref(props.isShow)
  const paginationVal = ref<any>({
    pageSize: 20,
    pageNum: 1,
  })
  const searchVal = ref<any>({
    pageSize: 20,
    pageNum: 1,
  })
  const submitLoading = ref(false)
  const targetingType = ref()
  const total = ref(0)
  const tableLoading = ref(false)
  const tableList = ref<Array<any>>([])
  const checkedTableList = ref<Array<any>>([])
  const selectIds = ref([])
  const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  }) as any

  function selectColumn(val: any) {
    selectIds.value = val
  }
  // 显示站点名称
  function getMarketplace(marketplaces: string) {
    let arr = marketplaces?.split(',')
    let names = arr?.map((val: string) => marketPlaceList[val]?.code)
    return names?.join(',')
  }
  // 切换适用类型
  function changeTargetingType() {
    checkedTableList.value = []
    getTableList()
  }
  //列表数据
  async function getTableList() {
    tableLoading.value = true
    let params = {
      marketplaceIds: props.currentData.applicableMarketplace?.split(','),
      ...searchVal.value,
      ...paginationVal.value,
    }
    if (props.currentData.policyType === 'TARGETING_POLICY') {
      // 广告位需要查询SP广告
      params.adTypes = ['SPONSORED_PRODUCTS']
    }
    let res: any
    if (targetingType.value === 'CAMPAIGN') {
      res = await getCampaignBaseList(params)
    } else if (targetingType.value === 'KEYWORD') {
      res = await getKeywordBaseList(params)
    } else if (targetingType.value === 'PRODUCT_TARGETING') {
      res = await getTargetingBaseList(params)
    }
    tableLoading.value = false
    tableList.value = res?.data?.data || []
    total.value = res?.data?.total || 0
  }
  // 分页
  function changePage(val: number) {
    paginationVal.value.pageNum = val
    getTableList()
  }
  function sizeChange(val: number) {
    paginationVal.value.pageSize = val
    getTableList()
  }
  // 批量选择数据
  const selectMulVal = (searchVal: any, item: any) => {
    item.value = searchVal
    startSearchByVal()
  }
  // 通过条件查询用户列表
  function startSearchByVal() {
    paginationVal.value.pageNum = 1
    searchVal.value = {}
    filterItem.value.forEach((el: FilterTableItem) => {
      searchVal.value[el.key] = el.value
    })
    getTableList()
  }
  // 关闭
  function closedDialog() {
    showPolicyItemDetail.value = false
    emit('closed')
  }
  // 添加活动
  function addItem(list: Array<any>) {
    // 不能重复加入
    const keyMap = {
      CAMPAIGN: 'campaignId',
      KEYWORD: 'keywordId',
      PRODUCT_TARGETING: 'targetId',
    }
    let key = keyMap[targetingType.value]
    list.forEach((el: any) => {
      if (!checkedTableList.value.some((item: any) => item[key] == el[key])) {
        checkedTableList.value.push(el)
      }
    })
  }
  // 添加应用
  async function submitData() {
    if (!checkedTableList.value.length) {
      Message.error('选择需要添加的应用')
      return false
    }
    let params: any = {
      policyId: props.currentData.id,
      targetingType: targetingType.value,
      policyType: props.currentData.policyType,
    }
    let policyTargetings = checkedTableList.value.map((el: any) => {
      let obj: any = {
        shopId: el.shopId,
        portfolioId: el.portfolioId,
        campaignId: el.campaignId,
        adType: el.adType,
      }
      if (targetingType.value === 'KEYWORD') {
        obj.adGroupId = el.adGroupId
        obj.keywordId = el.keywordId
      }
      if (targetingType.value === 'PRODUCT_TARGETING') {
        obj.adGroupId = el.adGroupId
        obj.targetId = el.targetId
      }
      return obj
    })
    params.policyTargetings = policyTargetings
    const res: any = await savePolicyTargeting(params)
    if (res) {
      Message.success('添加成功成功')
      emit('success')
      closedDialog()
      return true
    }
    return false
  }
  watchEffect(() => {
    if (props.shopList?.length) {
      filterItem.value[0].optionItems = props.shopList
    }
  })
</script>
<style lang="less" scoped>
  .arco-form-item {
    margin-bottom: 5px;
    margin-right: 10px;
  }
  .filter-item {
    margin-right: 8px;
    margin-bottom: 5px;
  }
  .checked-num {
    position: absolute;
    top: -30px;
    right: 0;
  }
</style>
